package com.sjf.day02.Stack;

import com.sjf.day02.Demo.Person;

import java.util.Scanner;

/**
 * 数组模拟堆栈
 *
 * @author <huangtang>
 * @since 2021/12/22 14:13
 **/
public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        String key="";
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while(loop){
            System.out.print("s:显示栈 \t");
            System.out.print("e:退出程序 \t");
            System.out.print("p:添加数据到栈中 \t");
            System.out.print("g:从栈中取出数据 \n");
            System.out.print("请输入: ");
            key = scanner.next();
            switch (key){
                case "s" :
                    stack.list();
                    break;
                case "p":
                    System.out.println("请输入一个数");
                    stack.push(scanner.nextInt());
                    break;
                case "e":
                    System.out.println("退出程序");
                    loop=false;
                    break;
                case "g":
                    System.out.println("取出的数为"+stack.pop());
                default:
                    break;
            }
        }
    }

}

class ArrayStack{
    private int maxSize;//栈大小
    public int top=-1;//指向栈顶元素
    public int[] stack;//数组模拟栈

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;//对数组作初始化
        stack = new int[maxSize];
    }

    /**
     * 遍历栈
     */
    public void list(){
        if(isEmpty()){
            System.out.println("栈空，没有数");
            return;
        }
        for (int i = top; i >=0 ; i--) {
            System.out.println(i+"："+stack[i]);
        }
    }

    /**
     * 入栈
     * @param value 入栈的值
     */
    public void push(int value){
        if(isFull()){
            System.out.println("栈满，不能入栈");
            return;
        }
       stack[++top] = value ;//栈顶指针前移后，赋值
    }

    /**
     * 出栈
     * @return 返回栈顶的数据
     */
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        return stack[top--];//取值后，栈顶指针-1

    }

    /**
     * 判断栈是否满
     * @return
     */
    public boolean isFull(){
        return top == maxSize-1;
    }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty(){
        return top == -1;
    }

}



